package com.machine.filling.net.http.network;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.machine.filling.MyApp;
import com.machine.filling.net.http.response.BaseHttpResponseBean;
import com.machine.filling.util.LogUtils;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by sperfan on 2018/3/1.
 *
 * @描述:
 */

public abstract class BaseHttpStringCallback implements Callback, IhttpCallback {
    private static final String TAG = "BaseHttpStringCallback";

    public static final String ERROR_REQUEST = "onError";//请求异常

    public static final String ERROR_RESPONSE = "response_exceptiono";//结果返回处理异常


    @Override
    public void onFailure(Call call, IOException e) {
        if (!MyApp.errorRequests.contains(call.request())) {
            Log.d(TAG, "异常请求提交: " + "提交失败");
            MyApp.errorRequests.add(call.request());
        }else{
            Log.d(TAG, "异常请求提交: " + "再次失败" + call.request().body());
        }

        Message msg = Message.obtain();
        msg.what = 1;
        msg.obj = e;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException{
        if (MyApp.errorRequests.contains(call.request())){
            Log.d(TAG, "异常请求提交: " + "这是老的request,已经删除");
            MyApp.errorRequests.remove(call.request());
        }else {
            Log.d(TAG, "异-常请求提交: " + "新的request已经通过");
        }

        Message msg = Message.obtain();
        msg.what = 0;
        msg.obj = response.body().string();
        mHandler.sendMessage(msg);
    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    String responseStr = (String) msg.obj;
                    BaseHttpResponseBean baseHttpResponseBean = null;
                    try {
                        LogUtils.d(TAG, "返回结果：====" + responseStr);
                        baseHttpResponseBean = new Gson().fromJson(responseStr, BaseHttpResponseBean.class);
                    } catch (Exception e) {
                        // TODO: 2018/4/13 0013 异常分门别类, 进行统一处理
                        onFailed(ERROR_RESPONSE, e.toString(), e);
                        LogUtils.e(TAG, "返回结果：请求失败onResponse===" + e.toString());
                        onFinished();
                    }
                    if (baseHttpResponseBean == null){
                        Log.d(TAG, "handleMessage() returned: 数据解析异常" );
                        onFailed(ERROR_REQUEST,"基本数据，解析异常",new RuntimeException("基本数据，解析异常"));
                    }else {
                        if (baseHttpResponseBean.isCode0000()) {
                            onSuccess(null, responseStr);
                        } else {
                            onFailed(baseHttpResponseBean.getCode(), baseHttpResponseBean.getMsg(), null);
                        }
                    }
                    onFinished();
                    break;

                case 1:
                    Exception e = (Exception) msg.obj;
                    if (e instanceof SocketTimeoutException){
                        onFailed(ERROR_REQUEST, "网络异常!", e);
                    }else if (e instanceof UnknownHostException) {
                        onFailed(ERROR_REQUEST,"网络异常",e);
                    }else{
                        onFailed(ERROR_REQUEST, e.toString(), e);
                    }

                    LogUtils.e(TAG, "返回结果：请求失败onError===" + e.toString());
                    onFinished();
                    break;
            }
        }
    };

}
